<template>
  <div class="edu-page-warp">
    <examination-search @reset="reset" @onSubmit="setQueryForm" :exam-type="false"></examination-search>
    <el-card>
      <div class="edu-page-title mg-top" style="margin-bottom:24px;">{{$t('examinationList.result')}}</div>
      <div class="edu-opertion-bar" style="margin-bottom:16px;">
        <div class="float-left">
          <el-input
            v-model="queryForm.condition"
            :placeholder="$t('examinationList.codition')"
            style="width:200px"
            @keyup.enter.native="onSubmit"
          >
            <i
              class="el-icon-search"
              slot="suffix"
              style="margin-top:10px;cursor:pointer"
              @click="onSubmit"
            ></i>
          </el-input>
        </div>
        <div class="float-right">
          <el-button @click="exportResult">{{$t("message.export")}}</el-button>
          <el-button @click="downResultTemplate">{{$t("exam.impotTemplate")}}</el-button>
          <el-button @click="importExcel">{{$t("message.import")}}</el-button>
          <!-- <el-button @click="addExamStudents" type="primary">{{$t('message.add')}}</el-button> -->
        </div>
      </div>
      <edu-table :url="api.pageUrl" ref="examinationLevelTable" size="mini" :order="false"
      @selection-change="chooseResult"
      >
        <el-table-column :label="$t('examinationLevel.studentId')">
          <template slot-scope="scope">{{scope.row.studentId}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.name')">
          <template slot-scope="scope">{{scope.row.studentName}}</template>
        </el-table-column>
        <el-table-column :label="$t('nonPublicCourseOpen.grade')" >
          <template slot-scope="scope">{{scope.row.grade}}</template>
        </el-table-column>
        <el-table-column :label="$t('nonPublicCourseOpen.college')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.facultyI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('nonPublicCourseOpen.major')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.majorI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.subject')">
          <template slot-scope="scope">{{scope.row.subjectI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationLevel.result')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.examResultsI18n}}</template>
        </el-table-column>
        <el-table-column :label="$t('examinationList.sugCourses')" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.sugCourses}}</template>
        </el-table-column>
        <el-table-column :label="$t('message.operating')">
          <template slot-scope="scope">
            <div v-if="scope.row.examFlag != 0">
              <el-button v-if="scope.row.examResults"
              type="text"
              @click="editById(scope.row.id,true)"
              size="mini"
              >{{$t('message.edit')}}</el-button>
              <el-button v-else
                type="text"
                @click="editById(scope.row.id,false)"
                size="mini"
              >{{$t('exam.input')}}</el-button>
            </div>
          </template>
        </el-table-column>
      </edu-table>
    </el-card>
    <edu-dialog
      :title="dialogTitle"
      width="45%"
      :visible.sync="showDeptsDialog"
      @close="resetAddForm"
      @confirm="submitForm"
    >
      <el-form
        :model="createForm"
        ref="createForm"
        label-width="85px"
        :rules="rules"
        class="createForm"
        label-position="right"
      >
        <el-row>
          <el-col :span="11">
            <el-form-item :label="$t('label.schoolTerm')">
              <CalendarSelect v-model="createForm.calendarId" :disabled="true"></CalendarSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('examinationLevel.subject')">
              <el-select v-model="createForm.subject" :disabled="true">
                <el-option
                  v-for="item in options.subjects"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="$t('examinationLevel.studentId')">
              <el-input v-model="createForm.studentId"  :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('examinationLevel.name')">
              <el-input v-model="createForm.studentName"  :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item :label="$t('nonPublicCourseOpen.grade')">
              <el-input v-model="createForm.grade" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('nonPublicCourseOpen.college')">
              <el-input v-model="createForm.facultyI18n" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11" >
            <el-form-item :label="$t('nonPublicCourseOpen.major')">
              <el-input v-model="createForm.majorI18n" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="examResults" :label="$t('examinationLevel.result')">
              <el-select v-model="createForm.examResults">
                <el-option
                  v-for="item in options.examResults"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item prop="sugCourses" :label="$t('examinationList.sugCourses')">
              <el-input type="textarea" v-model="createForm.sugCourses" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </edu-dialog>
    <edu-dialog
            :title="$t('exam.resultImport')"
            width="40%"
            ref="uploadDialog"
            @close="clearFiles"
            @confirm="uploadFile"
        >
            <el-form label-width="85px">
                <el-row>
                    <el-form-item>
                        <el-upload
                            ref="upload"
                            :data="{}"
                            :on-success="uploadDone"
                            :on-error="onError"
                            :auto-upload="false"
                            :multiple="false"
                            :on-change="(file, fileList)=>{this.fileList = fileList}"
                            :limit="1"
                            :accept="'application/vnd.ms-excel'"
                            action="api/welcomeservice/examinationStudents/import/examResult"
                        >
                            <el-button
                                slot="trigger"
                                size="small"
                                type="primary"
                            >{{$t('label.selectFile')}}</el-button>
                            <div
                                slot="tip"
                                class="el-upload__tip"
                            >{{$t('courseTake.uploadXLSFileOnly')}}</div>
                        </el-upload>
                    </el-form-item>
                </el-row>
            </el-form>
        </edu-dialog>
  </div>
</template>

<script>
import ExaminationSearch from "./components/ExaminationSearch";
import examinationStudentsApi from "common/src/api/welcomeService/examinationStudents";
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";

export default {
  name: "ExaminationResult",
  components: { ExaminationSearch },
  data() {
    return {
      api: examinationStudentsApi,
      showDeptsDialog: false,
      options: {
        examResults: [],
        subjects: [],
      },
      queryForm: {
        condition: "",
        calendarId:null,
        subject:"",
        grade:"",
        faculty: "",
        major: "",
        examResults:"",
      },
      createForm: {
        id:"",
        calendarId: "",
        subject: "",
        studentId: "",
        studentName: "",
        grade: "",
        faculty: "",
        facultyI18n: "",
        major: "",
        majorI18n: "",
        isExam: "",
        beginTime:"",
        endTime:"",
        examTime:"",
        remark: "",
        notice: "",
        examResults:"",
        sugCourses:""
      },
      chooseResults: [],
       rules: {
        examResults: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        sugCourses: [
          {
            required: true,
            message:this.$t("message.inputRequired"),
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      //筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_KCKM","X_RXKSCJ"]
      };
      queryDic(data).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            {
              subjects: "X_KCKM",
              examResults:"X_RXKSCJ"
            },
            res.data,
            this.options
          );
        }
      });
      //this.onSubmit();
    },
    setQueryForm(data){
        this.queryForm.calendarId = data.calendarId;
        this.queryForm.subject = data.subject;
        this.queryForm.grade = data.grade;
        this.queryForm.faculty = data.faculty;
        this.queryForm.major = data.major;
        this.queryForm.examResults = data.examResults;
        this.onSubmit();
    },
    exportResult() {
            let loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(255, 255, 255, .48)"
            });
            let data=_.cloneDeep(this.queryForm);
            data.ids = this.chooseResults.map(c => c.id);
            examinationStudentsApi.exportResult(data).then(res => {
                if (res.code == 200) {
                    this.delayRequest(res.data.key, loading);
                } else {
                    loading.close();
                }
            });
        },
        async delayRequest(key, loading) {
            await new Promise(resolve => setTimeout(resolve, 5000));
            examinationStudentsApi.getReportStatus(key)
                .then(res => {
                    if (res.code == 200 && res.data.status) {
                        let path =this.api.exportUrl + res.data.path;
                       // window.open(path);
                       window.location.href=path;
                        loading.close();
                    } else {
                        this.delayRequest(key, loading);
                    }
                })
                .catch(ex => {
                    this.delayRequest(key, loading);
                });
        },
        chooseResult(val) {
            this.chooseResults = val;
        },
        downResultTemplate(fileName){
          window.location.href = examinationStudentsApi.getResultTempalte();
        },
        importExcel(){
            this.$refs.uploadDialog.open();
        },
        clearFiles() {
            this.$refs.upload.clearFiles();
            this.fileList = [];
        },
         uploadFile() {
            this.$refs.upload.submit();
        },
        uploadDone(res, file, fileList) {
            if (res.code == 200) {
                this.$message({
                    type: "success",
                    message: this.$t("common.tips.uploadSuccess")
                });
                this.$refs.uploadDialog.close();
                this.onSubmit();
            } else {
                this.$message({
                    type: "error",
                    message: this.$t("common.tips.dataFormatError")
                });
                this.clearFiles();
            }
        },
        onError(err, file, fileList) {
            let msg = JSON.parse(err.message);
            this.$message({
                type: "error",
                message: msg.message
            });
        },
    onSubmit() {
      this.$refs.examinationLevelTable.search(this.queryForm);
    },
    reset() {
      this.queryForm.condition = "";
    },
    editById(id,flag) {
      examinationStudentsApi.findById(id).then(res => {
        if (res.code == 200) {
          Object.keys(res.data).forEach(k => {
            if (this.createForm.hasOwnProperty(k)) {
              this.createForm[k] =
                res.data[k] == 0 || res.data[k] == 1
                  ? res.data[k].toString()
                  : res.data[k];
            }
          });
          this.showDialog = true;
        }
      });
      //this.dialogTitle = this.$t("message.edit");
      if(flag){
        this.dialogTitle = this.$t('exam.editResult');
      }else{
        this.dialogTitle = this.$t('exam.inpoutResult');
      }
      this.showDeptsDialog = true;
    },
    resetAddForm() {
      this.$refs.createForm.clearValidate();
      this.createForm.id = ""
      this.createForm.calendarId = ""
      this.createForm.subject = ""
      this.createForm.studentId = ""
      this.createForm.studentName = ""
      this.createForm.grade = ""
      this.createForm.faculty = ""
      this.createForm.facultyI18n = ""
      this.createForm.major = ""
      this.createForm.majorI18n = ""
      this.createForm.isExam = ""
      this.createForm.beginTime = ""
      this.createForm.endTime = ""
      this.createForm.examTime = ""
      this.createForm.remark = ""
      this.createForm.notice = ""
      this.createForm.examResults = ""
      this.createForm.sugCourses = ""
    },
    submitForm() {
      this.$refs.createForm.validate(valid => {
        if (!valid) {
          return;
        }
        if (this.createForm.id) {
          examinationStudentsApi.updateById(this.createForm).then(response => {
            if (response.code == 200) {
              this.showDialog = false;
              this.$message({
                type: "success",
                message: this.$t("message.saveSuccess")
              });
              this.createForm.id = "";
              this.showDeptsDialog = false;
              this.onSubmit();
            }
          });
        } else {
          examinationStudentsApi.save(this.createForm).then(response => {
            if (response.code == 200) {
              this.showDialog = false;
              this.$message({
                type: "success",
                message: this.$t("message.saveSuccess")
              });
              this.showDeptsDialog = false;
              this.onSubmit();
            }
          });
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.createForm {
  .line {
    text-align: center;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}
</style>
